﻿package com.teaphy.coroutinecrawler.channel

import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.channels.consume
import kotlinx.coroutines.channels.consumeEach
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking

fun main() = runBlocking {
    val channel = Channel<Int>()

    launch {
        // 每间隔1s发送一条数据
        for (i in 0.until(5)) {

            if (!channel.isClosedForSend) {
                channel.send(i)
            }
            delay(1000)
        }
        channel.close()
        println("发送数据结束！")
    }

    // 对接收到的数据执行给定的action
    repeat(5) {
        channel.consume {
            println("接收到的数据为：$it")
        }
    }

    println("Done")
}